package cn.zorbus.laian.interfaces.facade;

import cn.zorbus.laian.application.service.SwitchService;
import cn.zorbus.laian.domain.entity.SwitchEntity;
import cn.zorbus.laian.infrastructure.common.Result;
import cn.zorbus.laian.infrastructure.common.command.ChangeSwitchCommand;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * create in 2023/12/4 01:46
 *
 * @author shishaodong
 * @version 0.0.1
 */
@Tag(name = "灯泡管理")
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Slf4j
@CrossOrigin
public class SwitchFacade {

    private final SwitchService service;

    private final Semaphore semaphore = new Semaphore(1);

    @Operation(description = "获取灯泡开关列表")
    @GetMapping("lights")
    public Result<Collection<SwitchEntity>> lamplightList() {
        return Result.success(service.switchList());
    }

    @Operation(description = "左边的 6 个开关")
    @PutMapping("/switch/main/{id}")
    public Result<String> switchMain(@PathVariable Integer id) throws InterruptedException {
        try {
            semaphore.acquire();
            service.switchMain(id);
            TimeUnit.MILLISECONDS.sleep(1000);
            return Result.success("");
        } finally {
            semaphore.release();
        }
    }

    @Operation(description = "右边的 7 个开关")
    @PutMapping("/switch/single")
    public Result<String> switchSingle(@RequestBody ChangeSwitchCommand command) throws InterruptedException {
        try {
            semaphore.acquire();
            service.switchSingle(command);
            TimeUnit.MILLISECONDS.sleep(1000);
            return Result.success("");
        } finally {
            semaphore.release();
        }
    }
}
